//import * as event from '@/utils/event';
import myModule from './utils/myModule';
const delay = myModule.get("delay");
const event = myModule.get('event');
const MyPlugin = {};
var isLogging = false; // 是否正在登录， 用来阻止多个请求，多次跳入登录页
import { mapState } from 'vuex';
MyPlugin.install = function (Vue) {

  // 注入组件
  Vue.mixin({

    computed: {
      ...mapState([
        'userInfo'
      ])
    },

    onUnload(){

      Object.assign(this.$data, this.$options.data())
    
    },

    methods: {

      async dispatch(type, options, showLoading=true, showErr=true){ // dispatch actions toggether
        var that = this, err, curTimeStamp;

        // Is it have Token except login
        if(!that.userInfo && type !== that.$actionsTypes.onLogin) return that.loginHandler(type, options),that.$mpvue.showToast({title: '未登录'}), "未登录"; //如果没有token，直接去登录页
        // Is it expired except login
        curTimeStamp = Date.now();
        
        if(type !== that.$actionsTypes.onLogin && curTimeStamp > that.userInfo.expires) return that.loginHandler(type, options),that.$mpvue.showToast({title: '未登录'}), "未登录";

        // 显示加载状态显示
         that.$mpvue.showNavigationBarLoading();
        showLoading && that.$mpvue.showLoading({
          title: '请求中...',
          mask: true
        });

        
        err = await that.$store.dispatch(type, options); // 请求
        

        showErr && err &&  that.$mpvue.showToast({  // action所有的错误提示
          title: err,
          showCancel: false
        });
        if (err === '未登录') {
          
          that.loginHandler(type, options);
          that.$store.commit(that.$mutationsTypes.DEL_USERINFO); // 登录过期，删除已有数据
        }else{
          // set expires to userInfo
          this.$store.commit(this.$mutationsTypes.SET_EXPIRES);
        }
        //console.log(err);
        // 关闭加载状态显示
        setTimeout(() => {
          that.$mpvue.hideNavigationBarLoading();
          showLoading && that.$mpvue.hideLoading();
        }, 500);
        

        that.$mpvue.stopPullDownRefresh();

        return err;
        

      },

      loginHandler (type, options) { // The user is not logged in and jumps to the login page
        // console.log(type);
        //console.log("loginHandler");
        var that = this;
        delay.doThing(() => {
          !isLogging? that.$router.push("/pages/login"): console.log('已阻止重复跳入登录页!');
          !isLogging && (isLogging = true); // 未正在登录才会改为正在登录
          // 发射一个登录监听事件,登录后再次请求数据
          event.on('logined', this, () => {
            isLogging && (isLogging = false);
            setTimeout(() => {
              this.dispatch(type, options);
            }, 800);
            
          });
        }, 1000)
      
       
      },

      navToAuntResume(actionType, auntId){ // 跳转到阿姨简历小程序 actionType： add or edit
        if(!this.userInfo) return;
        var { id, token} = this.userInfo;
        var { resumeMiniAppId, resumegMiniAppEnvVersion, resumeMiniAppUrl } = this.$config;

        var targMiniAppSpliceUrl = `${resumeMiniAppUrl}?admin_id=${id}&token=${token}&cource=1${actionType === 'add'? '': '&auntId=' + auntId}`;

        this.$mpvue.navigateToMiniProgram({
          appId: resumeMiniAppId,
          path: targMiniAppSpliceUrl,
          envVersion: resumegMiniAppEnvVersion,
          success(res) {
            console.log(res);
            // 打开成功
          },
          fail(res){
            console.log(res);
          }
        });
        this.closeControllerPopup && this.closeControllerPopup("showMenu");
      }

    }
  })
}
export default MyPlugin
